layui.define(['jquery','layer'], function(exports){
    var $ = layui.jquery,
        layer = layui.layer,
        appAjax = function() {
            this.options = {
                "close": false,
                "method": 'GET',
                "data": '',
                "dataType": 'json',
                "timeout": 50000,
                "cache": false,
                "confirm": false,
                "prompt": false,
                "isContinue": false,
                "loading": false //是否显示loading图片
            }
        };

    appAjax.prototype.init = function(config){
        var initThis = this;

        $.extend(true, this.options, config);
        $('.switch>span').each(function() {
            $(this).off('click').on('click', { ajax: initThis, that: $(this) }, initThis.switch);
        });

        $('.ajax-form').each(function () {

            $(this).off('click').on('click', { ajax: initThis, that: $(this) }, initThis.ajaxForm);
        });

        $('.btn-ajax').each(function () {
            $(this).off('click').on('click', { ajax: initThis, that: $(this) }, initThis.ajaxBtn);
        });

        $('.modal-box').each(function () {
            $(this).off('click').on('click', { ajax: initThis, that: $(this) }, initThis.modalBox);
        })

    };

    appAjax.prototype.switch = function(event){
        var params = $(this).parents('.switch').data('params');
        var initThis = event.data.ajax;

        if(params== undefined || params == ''){
            layer.msg('缺少必要的参数',{icon:5});
            return false;
        }
        var ipt = $(this).siblings('input.switch-input');
        $.ajax({
            type: params.method||'get',
            url: params.url,
            dataType: 'json',
            error: function(XMLHttpRequest) {
                initThis.callbackError(XMLHttpRequest);
                if(ipt.prop('checked')){
                    ipt.prop('checked',false);
                }else{
                    ipt.prop('checked',true);
                }
            },
            success: function(response) {
                if (!response.status) {
                    layer.msg(response.msg,{icon:5});
                    if(ipt.prop('checked')){
                        ipt.prop('checked',false);
                    }else{
                        ipt.prop('checked',true);
                    }
                }
            }
        });
    };
    appAjax.prototype.ajaxForm = function(event){
        var initThis = event.data.ajax;
        var options = initThis.options;
        var params = $(this).data('params');
        if (typeof params === 'string') {
            params = JSON.parse(params)
        }

        $.extend(true, options, params);

        var formElem = options.form;
        if (params.formId&& params.formId!=undefined) {
            formElem = params.formId;
        }

        if($(formElem).attr('action') == undefined){
            return false;
        }

        if(params.tips!=undefined && params.tips!=''){
            layer.confirm(params.tips,function (index) {

                var data = $(formElem).serialize();
                var method = $(formElem).attr('method');
                var config = {form:formElem,method:method,url:$(formElem).attr('action'),data:data};
                $.extend(true, options, config);
                initThis.ajax(initThis);
                layer.close(index);
            });
            return true;
        }else{
            var data = $(formElem).serialize();
            var method = $(formElem).attr('method');
            var config = {form:formElem,method:method,url:$(formElem).attr('action'),data:data};
            $.extend(true, options, config);
            initThis.ajax(initThis);
        }


    };
    appAjax.prototype.ajaxBtn = function(event){
        var initThis = event.data.ajax;
        var options = initThis.options;
        var params = $(this).data('params');
        if (undefined == params || null == params) {
            layer.alert('缺少必须参数');
            return false;
        }
        var url = params.url||$(this).attr('url')||$(this).attr('href');
        if(undefined == url || null == url){
            layer.alert('缺少提交地址');
            return false;
        }
        params.url = url;

        if(params.targetData){
            var data = $(params.targetData).serialize();
            if (!data) {
                layer.alert('请选择要操作的数据');
                return false;
            }
            params['data'] = data;
            delete params.targetData;
        }else{
            if(params.data){
                params['data'] = params.data;
            }
        }
        $.extend(true, options, params);
        initThis.confirm($(this));
    };

    appAjax.prototype.confirm = function(obj){
        var initThis = this;
        if (this.options.confirm) {
            var title = "";
            if (this.options.title) {
                title = this.options.title;
            } else {
                if (obj) {
                    title = obj.html().replace(/<i [\s\S]*<\/i>/ig, '');
                    title = '确认执行' + title + '操作吗'
                }
            }
            layer.confirm(title, { icon: 3, title: '提示' }, function(index) {
                initThis.prompt(obj)
                layer.close(index);
                return true;
            });
        }else{
            initThis.prompt(obj)
        }
    };

    appAjax.prototype.prompt = function(obj){
        var initThis = this;
        var prompt = this.options.prompt;
        if (prompt) {
            var title = "";
            if (prompt.title) {
                title = prompt.title;
            } else {
                if (obj) {
                    title = '请输入'+obj.html().replace(/<i [\s\S]*<\/i>/ig, '')+'缘由';
                }
            }
            if(prompt.name == '' || prompt.name == undefined){
                layer.alert('prompt缺少必须name参数');
                return false;
            }
            layer.prompt({
                formType: 2,
                title: title,
            }, function(value, index, elem){
                var promptField = prompt.name;
                var data = {};
                data[promptField] = value;
                if(initThis.options.data==''&&initThis.options.data==undefined){
                    initThis.options.data =  data;
                }else{
                    initThis.options.data+='&'+promptField+'='+value;
                }
                // console.log(initThis.options.data);
                // return false;
                initThis.ajax(initThis)
                layer.close(index);
            });
        }else{
            initThis.ajax(initThis)
        }
    };

    appAjax.prototype.ajax = function(obj){

        var initThis = obj;
        var options =initThis.options;
        if(options.loading){
            //layer.load(2, {time: 10*1000,shade:0.2});
            var loading = layer.msg('正在执行操作.......', {icon: 16,shade: 0.3,time: 10*1000 });
        }
        $.ajax({
            type: options.method,
            url: options.url,
            dataType: options.dataType,
            data: options.data,
            timeout: options.timeout,
            cache: options.cache
        }).done(function (response) {
            initThis.successCallBack(response);
            if(loading!=undefined){
                layer.close(loading);
            }

        }).fail(function (XMLHttpRequest) {
            initThis.callbackError(XMLHttpRequest);
            if(loading!=undefined){
                layer.close(loading);
            }
        });
    };
    
    appAjax.prototype.callbackError = function (XMLHttpRequest) {
        var status = XMLHttpRequest.status;
        switch (status) {
            case 422:
                var errors = XMLHttpRequest.responseJSON.errors;
                if(typeof errors == 'object') {
                    for (var index in errors) {
                        this.errorBox(errors[index][0]);
                        break;
                    }
                }else{
                    this.errorBox(XMLHttpRequest.responseJSON.msg);
                }
                break;
            case 404:
                this.errorBox('所请求的页面不存在或已被删除');
                break;
            case 200:
                if(XMLHttpRequest.responseText !=''){
                    layer.open({
                        type: 1,
                        content: XMLHttpRequest.responseText //这里content是一个普通的String
                    });
                }else{
                    this.errorBox(XMLHttpRequest.statusText);
                }
                break;
            default:
                this.errorBox('服务器内部错误');
        }
        return false;
    };

    appAjax.prototype.successCallBack = function (response) {
        if ((undefined == response) || (null == response) || this.options.close) return false;
        if (response.status) {
            if(this.options.isContinue){

            }
            var index;
            if (window.name) {
                index = parent.layer.getFrameIndex(window.name);
            }
            if ((undefined == response.url) || (null == response.url) || ("" == response.url)) {
                if (index) {
                    parent.layer.close(index);
                    parent.layer.msg(response.msg);

                } else {
                    layer.closeAll();
                    this.successBox(response.msg);
                }
                return false;
            } else {
                if ('reload' == response.url) {
                    if (index) {
                        parent.layer.close(index);
                        parent.location.reload();
                    } else {
                        location.reload();
                    }
                } else if (index) {
                    this.successBox(response.msg);
                    setTimeout(function () {
                        parent.layer.close(index);
                        parent.location.href = response.url;
                    }, 2000);
                } else {
                    this.successBox(response.msg);
                    setTimeout(function () {
                        location.href = response.url;
                    }, 2000);
                }
            }
        } else {
            this.errorBox(response.msg);
        }
        return true;
    };
    appAjax.prototype.errorBox = function(info){
        layer.msg(info,{icon: 5,shade:0.5});
    };
    appAjax.prototype.successBox = function(info){
        layer.msg(info,{icon: 6});
    };

    appAjax.prototype.modalBox = function(event){
        var initThis = event.data.ajax;
        //var options = initThis.options;
        var params = $(this).data('params');
        var url = $(this).attr('url')||$(this).attr('href')||params.url;
        if (undefined == url || null == url) {
            initThis.errorBox('请为当前元素配置访问链接');
            return false;
        }

        var _area = "auto";
        var title = '信息';
        if(undefined !=params && null !=params){
            if (params.area!= undefined&&params.area != "auto") {

                var width_height=params.area.split(",");
                var dpr = window.devicePixelRatio;
                var maxHeight = $(window).height() - 100 * dpr;
                var maxWidth = $(window).width() - 20 * dpr;
                if(width_height[0].indexOf('%')==-1){
                    var width = parseInt(width_height[0]),
                        _area_w = width + "px";
                    if (width > maxWidth) {
                        _area_w = (maxWidth) + "px";
                    }
                }else {
                    _area_w = width_height[0];
                }
                if(width_height[1].indexOf('%')==-1){
                    var height = parseInt(width_height[1]),
                        _area_h = height + "px";
                    if (height > maxHeight) {
                        _area_h = (maxHeight) + "px";
                    }
                }else{
                    _area_h = width_height[1];
                }
                _area = [_area_w,_area_h];
            }
            if(params.title!= undefined&&params.title != null){
                title = params.title;
            }
        }
       layer.open({
            type: 2,
            area:_area,
            title:title,
            maxmin:true,
            content: url
        });
        return false;
    };
    exports('appAjax', new appAjax());
});